package issr.market.controller;

import issr.market.db.impl.DBControllerImpl;
import issr.market.model.Utente;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

public class LoginUtenteController extends AbstractController {
	private static final long serialVersionUID = 1L;
	
	
	private static Logger logger = Logger.getLogger(LoginUtenteController.class);
	
	private String loginUtente;
	private String password;

	private String message;
	
	@Override
	public String execute(){
		
		String redirect = "accesso";
		
		HttpServletRequest request = getServletRequest();
		
		if(getActionToDo()!=null && getActionToDo().equals("login")){
			
			redirect = login(loginUtente, password, message, request.getSession());
			
		}
		else if(getActionToDo()!=null && getActionToDo().equals("logout")){
			logout(request.getSession());
		}
		else redirect = "login";
		
		return redirect;
	}
	
	
	public static String login(String loginUtente, String password, String message, HttpSession session){
		
		String redirect = "accesso";
		
		Utente utente = new DBControllerImpl().loginUtente(loginUtente, password);
		
		if(utente != null){
			logger.info("Login eseguito per user: "+loginUtente);
			session.setAttribute("userLogged", utente);
		}
		else{
			message = "<b>Login errato. Si prega di riprovare</b>";
			redirect = "login";
		}
		
		return redirect;
		
	}
	
	public static void logout(HttpSession session){
		logger.info("Eseguo logout");
		session.invalidate();
	}

	public String getLoginUtente() {
		return loginUtente;
	}

	public void setLoginUtente(String loginUtente) {
		this.loginUtente = loginUtente;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}
	
	
	
	

}
